package com.batchengine;

import com.batchengine.service.BatchEngineService;
import com.batchengine.startup.BatchServer;
import com.batchengine.startup.ServiceClient;
import org.apache.log4j.Logger;

import static com.batchengine.util.LoggingFactory.createLogger;
import static java.lang.System.setProperty;
import static java.net.InetAddress.getLocalHost;

/**
 * Created by sunil.incubator@yahoo.com.
 * User: sunil.kalva
 * Date: Jun 17, 2009
 */
public class BatchEngine extends BatchEngineService {

    private static BatchEngine engine;
    private static final Logger logger = createLogger();

    private static void start(int port) {
        BatchServer.start(port);
        logger.debug("started bash engine");
    }

    private static void stop(String host, int port, String password) {

        try {

            ServiceClient client = new ServiceClient(host, port);
            logger.debug("stdout>> ******* STOPPING SERVER NOW .... *******");
            client.match("Password: ", password, true);
            client.match("> ", "stop server", true);
            client.match("> ", "close", true);
            client.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private static void kill(String host, int port, String password) {

        try {

            ServiceClient client = new ServiceClient(host, port);
            client.match("Password: ", password, true);
            client.match("> ", "kill", true);
            client.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static BatchEngine getEngine() {
        return engine;
    }

    private static void printUsage() {

        System.out.println("Usage: ");
        System.out.println("java " + BatchEngine.class.getName() + " -start [options]");
        System.out.println("java " + BatchEngine.class.getName() + " -stop [options]");
        System.out.println("java " + BatchEngine.class.getName() + " -kill [options]");
        System.out.println("");
        System.out.println("-start              Starts the  TaskEngine Server.");
        System.out.println();
        System.out.println("-stop              Gracefully shuts down the  TaskEngine Server. By default it will");
        System.out.println("                      stop the server running on the local host. Use the -host argument");
        System.out.println("                      to stop a server running on a remote host.");
        System.out.println();
        System.out.println("-kill                 Ungracefully shuts down the  TaskEngine Server. By default it will");
        System.out.println("                      kill the server running on the local host. Use the -host argument");
        System.out.println("                      to kill a server running on a remote host.");
        System.out.println();
        System.out.println("-host <host>    IP address or host name of machine on which the  TaskEngine Server");
        System.out.println("                      is running. This argument is used by -stop and -kill arguments.");
        System.out.println();
        System.out.println("-port <port>    Specifies the control port of the  TaskEngine Server. This");
        System.out.println("                      overwrites any other configuration settings for the control port.");
        System.out.println();
        System.out.println("-vmargs <vmargs>      Specifies any arguments to the Java virtual machine of the ");
        System.out.println("                      TaskEngine Server. This argument is used by the -start argument.");
        System.out.println();
    }

    public static void setEngine(BatchEngine wEngine) {
        engine = wEngine;
    }

    public static void main(String[] args) {

        setSystemProperties();
        logger.debug("starting bash engine");
        String host = null;
        int port = 11111;
        boolean start = false;
        boolean stop = false;
        boolean kill = false;

        try {

            if(null == args || 0 == args.length) {
                args = new String[1];
                args[0] = "-start";
            }
            int count = 0;
            while(count < args.length) {

                if(args[count].equals("-start")) {
                    start = true;
                } else if(args[count].equals("-stop")) {
                    stop = true;
                } else if(args[count].equals("-kill")) {
                    kill = true;
                } else if(args[count].equals("-host")) {
                    host = args[++count];
                } else if(args[count].equals("-port")) {
                    port = Integer.parseInt(args[++count]);
                } else {
                    printUsage();
                    System.exit(1);
                }
                count++;
            }
        } catch(Exception e) {
            e.printStackTrace();
            printUsage();
            System.exit(1);
        }
        if(host == null) {
            host = "localhost";
        }

        if(start) {
            start(port);
        } else if(stop) {
            stop(host, port, null);
        } else if(kill) {
            kill(host, port, null);
        }
    }

    private static void setSystemProperties() {

//        String conf = getProperty("conf.file");
//        if(null == conf) {
//            setProperty("conf.file", "D:/mkhoj/codebase/bashengine_google/src/main/resources/conf/be.properties");
//            if(WINDOWS.contains(ENVIRONMENT)) {
//                setProperty("conf.file", "D:/mkhoj/codebase/bashengine_google/src/main/resources/conf/be.properties");
//            } else {
//                setProperty("conf.file", "/host//codebase/bashengine/settings/conf/be.properties");
//            }
//            conf = getProperty("conf.file");
//        }
//        setProperty("conf.file", conf);
//        logger.debug(String.format(">>>>>>>>>>>>>>> Reading configuration from file :: %s <<<<<<<<<<<<<<<<", getProperty("conf.file")));
        try {
            setProperty("com.sun.management.jmxremote", "");
            setProperty("com.sun.management.jmxremote.port", "9004");
            setProperty("com.sun.management.jmxremote.local.only", "false");
            setProperty("com.sun.management.jmxremote.authenticate", "false");
            setProperty("com.sun.management.jmxremote.ssl", "false");
            setProperty("java.rmi.server.hostname", getLocalHost().getHostAddress());
        } catch(Exception e) {
            logger.error("error@BatchEngineService#setSystemProperties");
        }
        try {
            System.out.println("----sleeping for entering debug mode----");
            Thread.sleep(1000 * 5);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}
